package com.heima.controller;

import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.heima.Result;
import com.heima.context.DoctorContext;
import com.heima.context.ResidentContext;
import com.heima.exception.DIYException;
import com.heima.service.AiChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import org.apache.commons.codec.digest.DigestUtils;
import com.heima.util.RedisUtil;

@RestController
@Tag(name = "智能助手接口")
public class AiChatController {
    private static final String MODEL = "qwen-tts";
    @Autowired
    private AiChatService aiChatService;
    @Autowired
    private RedisUtil redisUtil;

    @Operation(summary = "居民端智能助手聊天接口")
    @GetMapping("/resident/chat")
    public Flux<String> residentChat(@RequestParam String memoryId,@RequestParam String message) {
        if(ResidentContext.getCurrentId() == null){
            throw new DIYException("用户未登录");
        }
        String userId = ResidentContext.getCurrentId().toString();
        // 返回结果
        return aiChatService.chat("resident"+":"+ userId + ":" + memoryId, message);
    }
    @Operation(summary = "医生端智能助手聊天接口")
    @GetMapping("/doctor/chat")
    public Flux<String> doctorChat(@RequestParam String memoryId,@RequestParam String message) {
        if(DoctorContext.getCurrentId() == null){
            throw new DIYException("用户未登录");
        }
        String userId = DoctorContext.getCurrentId().toString();
        // 返回结果
        return aiChatService.chat("resident"+":"+ userId + ":" + memoryId, message);
    }

    @Operation(summary = "智能助手语音合成接口")
    @GetMapping(value = "/textToSpeech")
    public Result textToSpeech(@RequestParam String text) {
        try {
            // 生成缓存key
            String cacheKey = "tts:" + DigestUtils.md5Hex(text);

            // 从Redis中查询
            String cachedUrl = redisUtil.get(cacheKey);
            if (StringUtils.isNotBlank(cachedUrl)) {
                // 缓存命中，直接返回
                return Result.success(cachedUrl);
            }

            // 缓存未命中，调用API获取URL
            String audioUrl = callDashScopeTTS(text);

            // 将URL存入Redis，设置7天过期时间
            redisUtil.setWithExpirationDays(cacheKey, audioUrl, 7);
            return Result.success(audioUrl);
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            return Result.error("语音合成失败: " + e.getMessage());
        }
    }
    public String callDashScopeTTS(String  text) throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .model(MODEL)
                .apiKey(System.getenv("API_Key"))
                .text(text)
                .voice(AudioParameters.Voice.CHERRY)
                .build();
        MultiModalConversationResult result = conv.call(param);
        return result.getOutput().getAudio().getUrl();
    }

}
